//request.js 封装的函数


//测试服务器地址
var APP_URL = 'http://api-data.vjes.com/applet/';

//生产服务器地址
// var APP_URL = 'https://phgongxu.paohe.cn/applet/';

//轮播图地址前缀-测试地址
var imgUrl = 'http://api-data.vjes.com/image/show/';

//轮播图地址前缀-生产地址
// var imgUrl = 'https://phgongxu.paohe.cn/image/show/';

function islogin(call) {
  try {
    var that = this;
    //1.判断是否登录或者是否超时
    var exipreTime = wx.getStorageSync('exipreTime')
    //提前10分钟放弃token
    var now = new Date().getTime() / 1000 + 60 * 10
    if (exipreTime) {
      if (now > exipreTime) {
        //token超时s
        wx.removeStorageSync('exipreTime')
        wx.removeStorageSync('userInfo')
        wx.removeStorageSync('token')
        //去登录
        login((code, message) => {
          if (code < 1) {
            wx.showToast({
              title: message,
              icon: 'none',
              duration: 2000
            })
          } else {
            call()
          }
        })
      } else {
        call()
      }
    } else {
      //2.未登录，无登录信息，去登录
      login((code, message) => {
        if (code < 1) {
          wx.showToast({
            title: message,
            icon: 'none',
            duration: 2000
          })
        } else {
          call()
        }
      })
    }
  } catch (e) {
    reject(e)
    wx.showToast({
      title: '系统登录异常，请稍后再试！',
      icon: 'error',
      duration: 2000
    })
  }
}

var loginFlag = false

//核心请求入口
function request(url, data) {
  return new Promise((resolve, reject) => {
    if (loginFlag) {
      awaitRequest(300,url, data, resolve)
    } else {
      _request(url, data, resolve)
    }
  })
}

//等待登录
function awaitRequest(t,u,d,r){
  if (!loginFlag){
      _request(u, d, r)
  }else{
    t--
    if (t<0){
      wx.showToast({
        title: '系统登录超时！，请稍后再试！',
        icon: 'error',
        duration: 2000
      })
      return
    }
    setTimeout(() => {
      awaitRequest(t,u,d,r)
    }, 20)
  }
}

//
function _request(url, data, resolve) {
  loginFlag = true
  islogin(() => {
    loginFlag = false
    var exipreTime = wx.getStorageSync('exipreTime')
    var token = wx.getStorageSync('token')
    if (exipreTime) {
      post({
        data: data,
        token: token,
        url: url
      }, resolve)
    }
  })
}

/**
 * 发起网络请求
 */
function post(request, resolve) {
  wx.showLoading({
    title: '请求中...',
    icon: 'loading',
    mask: true
  })
  //对一些时间参数置空
  if (request.data) {
    if (request.data['createTime']) {
      request.data['createTime'] = null;
    }
    if (request.data['lastLoginTime']) {
      request.data['lastLoginTime'] = null;
    }
    if (request.data['modifyTime']) {
      request.data['modifyTime'] = null;
    }
  }

  wx.request({
    method: "post",
    dataType: "json",
    header: {
      "Authentication": request.token
    },
    url: APP_URL + request.url,
    data: request.data,
    success: function(resp) {
      wx.hideLoading()
      var data = resp.data;
      if (data.code > 0) {
        resolve(data)
      } else {
        wx.showToast({
          title: data.message,
          icon: 'none',
          duration: 2000
        })
      }
    },
    fail: function(data) {
      wx.hideLoading()
      wx.showToast({
        title: '网络请求异常，请稍后再试！',
        icon: 'none',
        duration: 2000
      })
    }
  })
}

function login(callback) {
  //登录系统-进行登录
  wx.getSystemInfo({
    success(res) {
      //console.log(res)
      wx.showLoading({
        title: '登录中...',
        icon: 'loading',
        mask: true
      })
      // 登录
      wx.login({
        success: logins => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          res["code"] = logins.code
          //发起网络请求
          wx.request({
            method: "post",
            dataType: "json",
            url: APP_URL + 'login',
            data: res,
            success: function(resp) {
              var data = resp.data;
              wx.hideLoading()
              if (data.code > 0) {
                wx.setStorageSync('userInfo', data.userInfo)
                wx.setStorageSync('exipreTime', data.exipreTime)
                wx.setStorageSync('token', data.token)
                console.log('登录成功')
                console.log(data)
                callback && callback(1) //成功
              } else {
                callback && callback(0, "登录失败:" + data.message)
              }
            },
            fail: function(data) {
              console.log(data)
              wx.hideLoading()
              callback && callback(0, "登录失败,网络异常！")
            }
          })
        }
      })
    }
  })
}

function getUserInfo() {
  var user = wx.getStorageSync('userInfo')
  return user || {}
}

module.exports = {
  post: request,
  login: login,
  getUser: getUserInfo,
  imgUrl: imgUrl,
  APP_URL: APP_URL
}